package com.example.voucher.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.voucher.common.CommonResponse;
import com.example.voucher.common.TenantCodeThreadLocal;
import com.example.voucher.config.VoucherChannelConfig;
import com.example.voucher.enums.VoucherTypeEnum;
import com.example.voucher.extension.ExtensionExecutor;
import com.example.voucher.service.VoucherService;

@Controller
@RequestMapping("/voucher")
public class VoucherController {

    @Autowired
    private ExtensionExecutor extensionExecutor;
    @Autowired
    private VoucherChannelConfig channelConfigurer;

    @RequestMapping("/genSalesVoucher")
    @ResponseBody
    public CommonResponse genSalesVoucher(@RequestParam("ids") List<Long> ids,
        @RequestParam("tenantCode") String tenantCode) {
        CommonResponse response = CommonResponse.success();
        TenantCodeThreadLocal.setTenantCode(tenantCode);
        genVoucherByVoucherType(ids, tenantCode, VoucherTypeEnum.SaleInvoice);
        return response;
    }

    @RequestMapping("/genPurchaseVoucher")
    @ResponseBody
    public CommonResponse genPurchaseVoucher(@RequestParam("ids") List<Long> ids,
        @RequestParam("tenantCode") String tenantCode) {
        CommonResponse response = CommonResponse.success();
        TenantCodeThreadLocal.setTenantCode(tenantCode);
        genVoucherByVoucherType(ids, tenantCode, VoucherTypeEnum.PurchaseInvoice);
        return response;
    }

    private void genVoucherByVoucherType(List<Long> ids, String tenantCode, VoucherTypeEnum voucherType) {
        // 查询租户扩展点配置：VoucherService的扩展点用于判断是否走公共的逻辑，还是1个租户一套生成凭证代码的逻辑
        if (channelConfigurer.isEasChannel(tenantCode)) {
            extensionExecutor.executeVoidByTenantCode(VoucherService.class, tenantCode, t -> t.genEasVoucher(ids, voucherType));
        } else if (channelConfigurer.isNcChannel(tenantCode)) {
            extensionExecutor.executeVoidByTenantCode(VoucherService.class, tenantCode, t -> t.genNcVoucher(ids, voucherType));
        } else {
            throw new RuntimeException(String.format("找不到租户=【{%s}】推送凭证到哪个第三方相关的配置", tenantCode));
        }
    }

}
